package com.uinfor.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.uinfor.entity.Payment;
import com.uinfor.entity.Result;
import com.uinfor.service.IPaymentService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @descripttion:
 * @Author: WZH
 * @Date :2021/2/3  11:40
 **/
@RestController
public class TestController {
    public static final String SERVICE_URL="http://nacos-payment-provider";
    @Resource
    private RestTemplate restTemplate;

    @RequestMapping("/consumer/payment/{id}")
//    @SentinelResource(value = "fallback")//没有配置
//    @SentinelResource(value = "fallback",fallback = "handlerFallback")//fallback 负责业务异常
    @SentinelResource(value = "facllback",blockHandler = "blockHandler")
    public Result<Payment> test(@PathVariable("id") Long id) throws Exception {
        Result forObject = restTemplate.getForObject(SERVICE_URL + "/payment/" + id, Result.class, id);
        if (id==5){
            throw new IllegalAccessException("非法参数异常");
        }else if (forObject.getData()==null){
            throw new NullPointerException("该id没有数据");
        }
        return forObject;
    }
//    public Result<Payment> handlerFallback(@PathVariable("id") Long id,Throwable e) throws Exception{
//        Payment aNull = new Payment(id, "null");
//        return new Result<>(444,"兜底方法，错误就会返回这个方法，错误内容为"+e.getMessage(),aNull);
//    }
    public Result<Payment> blockHandler(@PathVariable("id") Long id, BlockException blockException) throws Exception{
        Payment aNull = new Payment(id, "null");
        return new Result<>(444,"兜底方法，管的是配置违规，错误内容为"+blockException.getMessage(),aNull);
    }
    @Resource
    private IPaymentService iPaymentService;
    @GetMapping("/connsumer/paymentSql/{id}")
    public Result<Payment> testOpen(@PathVariable("id") Long id){
        Result<Payment> paymentResult = iPaymentService.paymentSql(id);
        return paymentResult;
    }

}
